(function (window, $,Camera) {
    $(function () {
        // 设置iframe的高度，非精准适应屏幕高度
        var docHeight = $(document).height();
        $('#reportContainer, #applicationContainer').height(docHeight - 300);
        var cardModel = [
            {type: "1", name: "身份证"},
            {type: "2", name: "户口簿"},
            {type: "3", name: "护照"},
            {type: "4", name: "军官证"},
            {type: "5", name: "士兵证"},
            {type: "6", name: "港澳居民来往内地通行证"},
            {type: "7", name: "台湾同胞来往内地通行证"},
            {type: "8", name: "临时身份证"},
            {type: "9", name: "外国人居住证"},
            {type: "10", name: "警官证"},
            {type: "11", name: "香港身份证"},
            {type: "12", name: "澳门身份证"},
            {type: "13", name: "台湾身份证"},
            {type: "14", name: "其他证件"}
        ];
        var vm = avalon.define({
            $id: 'justiceInquiryPage',
            cardModel: cardModel,
            step: 1,
            justice1ImgArr:[],
            justice2ImgArr:[],
            letterImgUrlPath:{},
            introImgUrlPath:{},
            promiseImgUrlPath:{},
            reqReportVo:{},
            errMsg: {},
            application: {
                content: ''
            },
            report: {
                content: ''
            },
            inquiryModel:{
                inquiryType:3,
                userName:'',
                cardNum:'',
                cardType:'1',
                justiceName1:'',
                justiceCardType1:'1',
                justiceCardNum1:'',
                justiceIdcardImgUrl1:'',
                justiceName2:'',
                justiceCardType2:'1',
                justiceCardNum2:'',
                justiceIdcardImgUrl2:'',
                letterImgUrl:'',
                introImgUrl:'',
                promiseImgUrl:'',
                fileUrl:''
            },
            showError: function (reasons) {
                var result = {};
                for (var i = 0; i < reasons.length; i++) {
                    var reason = reasons[i];
                    var element = reason.element;
                    var name = element.id;
                    if (name) {
                        result[name] = reason;
                    }
                }
                vm.errMsg = result;
            },
            gotoStep: function (step) {
                vm.step=step;
            },
            cardTypeChange:function(type){
                if(type==1){
                    vm.justice1ImgArr.clear();
                }else {
                    vm.justice2ImgArr.clear();
                }
            },
            isIdCard:function(type){
                if(type==1){
                    return vm.inquiryModel.justiceCardType1 == 1;
                }else if(type==2){
                    return vm.inquiryModel.justiceCardType2 == 1;
                }
            },
            readIdCard: function (type) {
                var idCardData = Camera.readIdCardData();
                //type 1 司法1  2 司法2
                if(type==1){
                    vm.inquiryModel.justiceCardNum1=idCardData.id;
                    vm.inquiryModel.justiceName1=idCardData.name
                    vm.justice1ImgArr.clear();
                    vm.justice1ImgArr.push({id:'',path:idCardData.front});
                    vm.justice1ImgArr.push({id:'',path:idCardData.back});
                }else{
                    vm.inquiryModel.justiceCardNum2=idCardData.id;
                    vm.inquiryModel.justiceName2=idCardData.name;
                    vm.justice2ImgArr.clear();
                    vm.justice2ImgArr.push({id:'',path:idCardData.front});
                    vm.justice2ImgArr.push({id:'',path:idCardData.back});
                }
                Camera.stopIdCard();
                vm.upload(type);
            },
            removePic: function (index, type) {
                if (type == 1) {
                    vm.justice1ImgArr.splice(index, 1);
                } else if(type==2) {
                    vm.justice2ImgArr.splice(index, 1);
                }
            },
            upload:function(type){
                var imgList=new Array();
                if(type==1){
                    imgList=vm.justice1ImgArr;
                }else if(type==2){
                    imgList=vm.justice2ImgArr;
                }else if(type==3){
                    imgList.push(vm.introImgUrlPath);
                }else if(type==4){
                    imgList.push(vm.letterImgUrlPath);
                }else if(type==5){
                    imgList.push(vm.promiseImgUrlPath);
                }
                if(imgList.length<1){
                    return;
                }
                vm.uploadPhoto(imgList,type,vm.uploadCallback);
            },
            uploadCallback:function(data,type){
            	
            	if(data.code == 'SID_CHECK_FAIL'){
						location.href = data.data;
						return;
				}
            	
                if(type==1){
                    for(var i=0;i<data.data.length;i++){
                    	vm.inquiryModel.justiceIdcardImgUrl1 += data.data[i].id + ";";
                        vm.justice1ImgArr[i].id=data.data[i].id;
                    }
                }else if(type==2){
                    for(var i=0;i<data.data.length;i++){
                    	vm.inquiryModel.justiceIdcardImgUrl2 += data.data[i].id + ";";
                        vm.justice2ImgArr[i].id=data.data[i].id;
                    }
                }else if(type==3){
                    vm.inquiryModel.introImgUrl=data.data[0].id;
                }else if(type==4){
                    vm.inquiryModel.letterImgUrl=data.data[0].id;
                }else if(type==5){
                    vm.inquiryModel.promiseImgUrl=data.data[0].id;
                }
            },
            uploadPhoto:function (imgList,type,callback){
                var prefix = 'data:image/png;base64,'; // 注意图片格式
                var prefixJpeg = "data:image/jpeg;base64,";
                var vo={};
                var targetList=[];
                vo.sourceType=2;
                if(imgList.length>0){
                    for(var i=0;i<imgList.length;i++){
                        targetList.push(imgList[i].path.replace(prefix,"").replace(prefixJpeg,""));
                    }
                    vo.base64Files=targetList;
                    $.ajax({
                        url: 'file/upload/base64',
                        data: JSON.stringify(vo),
                        contentType: "application/json; charset=UTF-8",
                        type: "POST",
                        dataType:"json",
                        success: function (responseJSON) {
                            alert("上传成功");
                            callback(responseJSON,type);
                        },
                        error:function(){
                            alert("上传失败");
                        }
                    });
                }
                return true;
            },
            inquiryToApplyTbl: function (resp) {
                vm.inquiryModel.id=resp.data.id;
                vm.reqReportVo = resp.data;
                vm.reqReportVo.html = "";
                vm.gotoStep(2);
                $('#reportContainer')[0].contentDocument.body.innerHTML = resp.data.html;
                $('#reportContainer')[0].contentDocument.body.style.cssText = 'background-color: #ffffff;';
            },
            scan:function(type,deviceType){
                var img=Camera.scan(deviceType);
                if(img=='undefined '||img=='data:image/jpeg;base64,'){
                    return;
                }
                if(type==1){//1司法
                    vm.justice1ImgArr.push({id:'',path:img});
                }else if(type==2){//2司法
                    vm.justice2ImgArr.push({id:'',path:img});
                }else if(type==3){//协查函
                    vm.introImgUrlPath={id:'',path:img};
                }else if(type==4){//介绍信
                    vm.letterImgUrlPath={id:'',path:img};
                }else if(type==5){//保证书
                    vm.promiseImgUrlPath={id:'',path:img};
                }
                vm.upload(type);
            },
            apply:function(){
                if(vm.justice1ImgArr.length>0){
                    var idStr='';
                    for(var i=0;i<vm.justice1ImgArr.length;i++){
                        idStr+=vm.justice1ImgArr[i].id+";";
                    }
                    if(idStr.length>0){
                        vm.inquiryModel.justiceIdcardImgUrl1=idStr.substring(0,idStr.length-1);
                    }
                }
                if(vm.justice2ImgArr.length>0){
                    var idStr1='';
                    for(var y=0;y<vm.justice2ImgArr.length;y++){
                        idStr1+=vm.justice2ImgArr[y].id+";";
                    }
                    if(idStr1.length>0){
                        vm.inquiryModel.justiceIdcardImgUrl2=idStr.substring(0,idStr1.length-1);
                    }
                }

                var data = vm.inquiryModel.$model;
                $.ajax({
                    url: 'inquiry/justice/save',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            vm.inquiryToApplyTbl(resp);
                            forbidLeftAndTop.forbid();
                        } else {
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	layer.msg(resp.msg == "" ? "查询失败" : resp.msg);
                        }
                    },
                    error:function(){
                        alert("申请失败");
                    }
                });
            },
            printReport: function () {
                // window.print();
                // 这里需要弹框出来提示 完成 / 重新打印
                if (confirm("你确定要打印该报告吗？")) {
                    var data = {};
                    data.id = vm.inquiryModel.id;
                    $.ajax({
                        url: 'inquiry/credit/print',
                        type: 'post',
                        data: data,
                        dataType:"json",
                        success: function (resp) {
                            if (resp.code === 'SUCCESS') {
                                window.commonPrint('reportContainer');
                                // $('#reportContainer')[0].contentWindow.print();
                            }
                        }
                    });
                } else {
                    //alert("点击了取消");
                }
            },
            cancelPrintReport: function () {
                if (confirm("你确定要取消打印吗？")) {
                    // 跳转到初始界面
                    menuFullUrl('inquiry/justice')
                    forbidLeftAndTop.cancel();
                }
            },
            validate: {
                onManual: $.noop,
                onValidateAll: function(reasons){
                    vm.showError(reasons);
                    if (!reasons.length) {
                        vm.apply();
                    }
                },

                onError: function (reasons, ev) {
                    vm.showError(reasons);
                },
                onSuccess: function (reasons, ev) {
                    vm.errMsg = '';
                },
                // onComplete: avalon.noop,//针对单个表单元素
                // onReset: avalon.noop, //针对单个表单元素
                // validateInBlur: true, // {Boolean} true，在blur事件中进行验证,触发onSuccess, onError, onComplete回调
                // validateInKeyup: true, // {Boolean} true，在keyup事件中进行验证,触发onSuccess, onError, onComplete回调
                validateAllInSubmit: false // {Boolean} true，在submit事件中执行onValidateAll回调
                // resetInFocus: true, // {Boolean} true，在focus事件中执行onReset回调,
                // deduplicateInValidateAll: false // {Boolean} false，在validateAll回调中对reason数组根据元素节点进行去重
            },
        });
        avalon.scan($("#page-content-wrapper")[0]);
        window.setTimeout(function () {
            Camera.destroy();
            Camera.init({
                container: '#videoContainer',
                id: 'ca',
                width:300,
                height:250,
                viewWidth:290,
                viewHeight:215,
                type: 4,
                facRect:true
            });
        }, 1000);
    });

}(window, jQuery,Camera));